import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.junit.Test;

import java.util.Properties;

public class Listener {

    private static ZkClient zkClient;
    public static final String server = "linux01:2181,linux02:2181,linux03:2181";
    public static final String path = "/zktask/dblink";

    public static void monitor() {
        //获取zk对象
        zkClient = new ZkClient(server);
        zkClient.setZkSerializer(new ZkStrSerializer());
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("zk中数据库连接信息发生改变，现在的信息为：");
//                String info = zkClient.readData(s, true);
                System.out.println(String.valueOf(o));
                Properties pro = new Properties();
                Utils.loadData(pro,String.valueOf(o));
                //释放旧的数据库连接池
                ConnectionManager.clearPool();
                System.out.println("旧数据库连接池已释放!!!");
                //创建新的数据库连接池
                Utils.createDbPool(pro);
                System.out.println("数据库连接池已创建!!!");
            }
            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("zk中数据库连接信息已被删除");
            }
        });
    }
}
